<template>
  <div class="custom-form-making">
    <fc-designer
      ref="designer"
      :menu="onlyBasicMenu"
      style="height: 100%"
      :config="config"
      @save="handleSave"
      @clear="handleClear"
    />
  </div>
</template>

<script lang="ts" setup>
import { ref, onActivated } from 'vue'
import * as CustomFormApi from '@/api/system/customform'

defineOptions({ name: 'CustomForm' })
const message = useMessage() // 消息弹窗

const designer = ref()

const config = ref({
  showSaveBtn: true, // 是否显示保存按钮
  showPreviewBtn: false, // 是否显示预览按钮
  showLanguage: false, // 是否显示语言切换按钮
  showTemplate: false, // 是否显示模板按钮
  showDevice: false, // 是否显示多端适配按钮
  showJsonPreview: false
})

// 仅显示：输入框、计数器、单选框、多选框、日期、选择器
const onlyBasicMenu = [
  {
    title: '基础组件',
    name: 'base',
    list: [
      { label: '输入框', name: 'input', icon: 'icon-input' },
      { label: '计数器', name: 'inputNumber', icon: 'icon-number' },
      { label: '单选框', name: 'radio', icon: 'icon-radio' },
      { label: '多选框', name: 'checkbox', icon: 'icon-checkbox' },
      { label: '日期', name: 'datePicker', icon: 'icon-date' },
      { label: '选择器', name: 'select', icon: 'icon-select' }
    ]
  }
]

// 获取配置数据
const getProfile = async () => {
  try {
    const data = await CustomFormApi.getProfile()
    if (data && designer.value) {
      // 设置表单设计器的数据
      const { rule, options } = JSON.parse(data)
      // 回显设计的表单
      designer.value.setOptions(options)
      designer.value.setRule(rule)
    }
  } catch (error) {
    console.error('获取配置失败:', error)
  }
}

// 保存配置数据
const saveProfile = async (profileData: any) => {
  try {
    await CustomFormApi.saveProfile(profileData)
    message.success('保存成功')
  } catch (error) {
    console.error('保存配置失败:', error)
  }
}

// 监听设计器的保存事件
const handleSave = (formData: any) => {
  saveProfile(JSON.stringify(formData))
}

const handleClear = () => {
  saveProfile('')
}

onActivated(() => {
  getProfile()
})
</script>

<style scoped>
.custom-form-making {
  height: calc(
    100vh - var(--top-tool-height) - var(--tags-view-height) - var(--app-content-padding) -
      var(--app-content-padding) - 2px
  );
}

/* 设计器主内容区域去掉默认 padding（需要穿透到子组件） */
:deep(._fc-m-con) {
  padding: 20px 20px 0 20px !important;
}
/** 隐藏没有用的控件 */
:deep(._fc-m-tools .line),
:deep(._fc-m-tools ._fd-input-btn),
:deep(._fc-l-menu) {
  display: none !important;
}

/* 隐藏顶部切换 */
:deep(.fc-designer .el-header) {
  display: none !important;
}

:deep(.fc-designer ._fc-h) {
  display: none !important;
}

:deep(.fc-designer ._fc-tabs) {
  display: none !important;
}
</style>
